<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>包围盒，实现物体的最大化，正交投影</title>
    <style>
      body {
        margin: 0;
        overflow: hidden;
        /* 隐藏body窗口区域滚动条 */
      }
    </style>
    <!--引入three.js三维引擎-->
    <!-- <script src="http://www.yanhuangxueyuan.com/versions/threejsR92/build/three.js"></script> -->
    <!-- <script src="http://www.yanhuangxueyuan.com/threejs/build/three.js"></script> -->
    <!-- Three.js-master 包示例中的用法 examples/js/controls/OrbitControls.js  版本要匹配-->
    <script type="importmap">
      {
        "imports": {
          "three": "../../node_modules/three/build/three.module.js",
          "three/addons/": "../../node_modules/three/examples/jsm/"
        }
      }
    </script>
  </head>
  <body>
    <script type="module">
      import {
        RAFTime,
        sphereMesh,
        cylinderMesh,
        v2ToV3,
      } from "../../util/index.js";

      import * as THREE from "three";
      import { OrbitControls } from "three/addons/controls/OrbitControls.js";
      import Stats from "three/addons/libs/stats.module.js";
      import { GUI } from "three/addons/libs/lil-gui.module.min.js";

      /**
       * 创建场景对象Scene
       */
      var scene = new THREE.Scene();
      // 创建一个组表示所有的雨滴
      var group = new THREE.Group();

      // ------------------------------------------------------------------------形状几何体
      const shape = new THREE.Shape([
        new THREE.Vector3(0, 0, 0),
        new THREE.Vector3(100, 0, 0),
        new THREE.Vector3(100, 100, 0),
        new THREE.Vector3(0, 100, 0),
      ]);
      const shapeGeometry = new THREE.ShapeGeometry(shape);
      const shapeMesh = new THREE.Mesh(
        shapeGeometry,
        new THREE.MeshStandardMaterial({
          color: "#FF0000",
          side: THREE.DoubleSide,
          transparent: true,
          opacity: 0.5,
        })
      );

      // -------------------------------------------------------------------------1.模型的包围盒
      const box3 = new THREE.Box3();
      box3.expandByObject(shapeMesh);
      const box3Size = new THREE.Vector3();
      box3.getSize(box3Size);
      console.log("box3Size---", box3Size);
      const box3Center = new THREE.Vector3();
      box3.getCenter(box3Center);
      console.log("box3Center---", box3Center);

      scene.add(shapeMesh);

      // -------------------------------------------------------------------------2.正交相机，最大化显示物体
      var width = window.innerWidth; //窗口宽度
      var height = window.innerHeight; //窗口高度
      var k = width / height; //窗口宽高比
      var s = box3Size.y / 2;
      //创建相机对象
      var camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000);
      camera.position.set(box3Center.x, box3Center.y, box3Center.z + 200); //设置相机位置
      // camera.lookAt(box3Center.x, box3Center.y, box3Center.z); //设置相机方向(指向的场景对象)，轨迹控制器controls.target.set自动执行这一步

      /**
       * 辅助坐标系 参数250表示坐标系大小，可以根据场景大小去设置
       */
      var axesHelper = new THREE.AxesHelper(1000);
      scene.add(axesHelper);

      // 平行光
      var directionalLight = new THREE.DirectionalLight(0xffffff, 1);
      // 平行光辅助对象
      const directionalLightHelper = new THREE.DirectionalLightHelper(
        directionalLight,
        10
      );
      scene.add(directionalLightHelper);
      // 设置光源位置
      directionalLight.position.set(60, 60, 60);
      scene.add(directionalLight);
      // 设置用于计算阴影的光源对象
      directionalLight.castShadow = true;
      // 设置计算阴影的区域，最好刚好紧密包围在对象周围
      // 计算阴影的区域过大：模糊  过小：看不到或显示不完整
      directionalLight.shadow.camera.near = 0.5;
      directionalLight.shadow.camera.far = 300;
      directionalLight.shadow.camera.left = -100;
      directionalLight.shadow.camera.right = 100;
      directionalLight.shadow.camera.top = 200;
      directionalLight.shadow.camera.bottom = -200;
      // 设置mapSize属性可以使阴影更清晰，不那么模糊
      directionalLight.shadow.mapSize.set(1024, 1024);
      console.log(directionalLight.shadow.camera);

      //环境光
      var ambient = new THREE.AmbientLight(0x050505);
      scene.add(ambient);

      /**
       * 创建渲染器对象
       */
      var renderer = new THREE.WebGLRenderer();
      renderer.setSize(width, height); //设置渲染区域尺寸
      renderer.setClearColor(0xb9d3ff, 1); //设置背景颜色
      // 设置渲染器，允许光源阴影渲染
      renderer.shadowMap.enabled = true;
      document.body.appendChild(renderer.domElement); //body元素中插入canvas对象

      // 渲染性能工具stats.js
      const stats = new Stats();
      stats.setMode(1);
      document.body.appendChild(stats.domElement);

      // 交互界面工具gui.js
      const gui = new GUI();
      gui.close();
      //改变交互界面style属性
      gui.domElement.style.right = "0px";
      gui.domElement.style.width = "300px";

      // 界面分组
      const directionalLightFolder = gui.addFolder("平行光父文件夹");

      // directionalLightFolder.close();

      directionalLightFolder
        .addColor(directionalLight, "color")
        .name("平行光颜色")
        .step(0.1)
        .onChange(function (value) {
          directionalLight.color.set(value);
        });

      const directionalLightSubFolder =
        directionalLightFolder.addFolder("平行光子文件夹");

      directionalLightSubFolder
        .add(directionalLight, "intensity", 0, 10)
        .name("平行光强度")
        .step(0.1);

      // // 监听鼠标、键盘事件，实现 旋转/缩放/平移
      // function render() {
      //   renderer.render(scene, camera); //执行渲染操作
      // }

      // 递归函数,每1/60秒左右,调用一次自己
      const render = RAFTime((t) => {
        stats.update();
        renderer.render(scene, camera); //执行渲染操作
      });

      // 启动渲染---requestAnimationFrame周期性的渲染
      render();

      // -------------------------------------------------------------------------3.轨迹控制器的初始方向与相机一致，并更新
      var controls = new OrbitControls(camera, renderer.domElement);
      controls.target.set(box3Center.x, box3Center.y, box3Center.z);
      controls.update();
      // 监听鼠标、键盘事件
      // controls.addEventListener("change");

      // 窗口大小变化后，设置画布 => 设置相机参数 => 更新投影矩阵
      window.onresize = function () {
        // 重置渲染器输出画布canvas尺寸
        renderer.setSize(window.innerWidth, window.innerHeight);
        // 全屏情况下：设置观察范围长宽比aspect为窗口宽高比
        let k = window.innerWidth / window.innerHeight;
        camera.left = -s * k;
        camera.right = s * k;
        // 渲染器执行render方法的时候会读取相机对象的投影矩阵属性projectionMatrix
        // 但是不会每渲染一帧，就通过相机的属性计算投影矩阵(节约计算资源)
        // 如果相机的一些属性发生了变化，需要执行updateProjectionMatrix ()方法更新相机的投影矩阵
        camera.updateProjectionMatrix();
      };
    </script>
  </body>
</html>
